﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VirtualOrg.Mobile.DBAccess;
using VirtualOrg.Mobile.Models;
using VirtualOrg.Mobile.Process;

namespace VirtualOrg.Mobile.Controllers
{
    public class VorgController : Controller
    {
        //
        // GET: /Vorg/

        public ActionResult Create()
        {
            if (Request.Cookies.AllKeys.Contains("vorguser"))
            {
                ViewData["catlist"] = VOrgProcess.GetCategoryList();
                ViewData["subcatlist"] = new List<SelectListItem>();
                return View();
            }
            else
            {
                return RedirectToAction("LogOn", "Account");
            }
        }

        public ActionResult Edit()
        {
            return View();
        }

        public ActionResult Info()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(OrgModel model)
        {
            if (Request.Cookies.AllKeys.Contains("vorguser"))
            {
                if (ModelState.IsValid)
                {
                    try
                    {
                        using (VOrgStoreDataContext datacontext = new VOrgStoreDataContext())
                        {
                            long userId = Convert.ToInt64(Request.Cookies["vorguser"].Value.Split('-')[0]);
                            datacontext.CreateOrganization(model.Title, model.Tagline, model.Description, "", "", userId, model.Category, model.SubCategory, "");
                            return RedirectToAction("List", "Vorg");
                        }
                    }
                    catch
                    {
                        ModelState.AddModelError("", "Error while creating organization");
                        
                    }
                }

                //ViewData["catlist"] = VOrgProcess.GetCategoryList();
                //ViewData["subcatlist"] = new List<SelectListItem>();
                return View(model);
            }
            else
            {
                return RedirectToAction("LogOn", "Account");
            }
        }

        public ActionResult List()
        {
            long userId = 0;
            if (Request.Cookies.AllKeys.Contains("vorguser"))
            {
                userId = Convert.ToInt64(Request.Cookies["vorguser"].Value.Split('-')[0]);
                return View(VOrgProcess.GetOrgList(userId));
            }
            else
            {
                return RedirectToAction("LogOn", "Account");
            }
        }

        [HttpPost]
        public JsonResult GetSubCategory(long categoryId)
        {
            var subcatlist = VOrgProcess.GetSubCategoryList(categoryId);
            
            return Json(subcatlist);
        } 
    }
}
